import time
from datetime import datetime

import pandas
import pandas as pd
import geopandas as geo
import matplotlib.pyplot as plt
from math import cos, sin, atan2, sqrt, pi, radians, degrees
from loguru import logger
import sys

# pandas show all rows
pd.set_option('display.max_rows', None)
# pandas show all col
pd.set_option('display.max_columns', 20)
# dataframe打印不换行
pd.set_option('display.width', 5000)

#####################################################
# Divide the grid for each order    为每一个订单划分网格 并且 删除出发地和到达地在同一个网格的订单
#####################################################

# ---------------------function-----------------------

logger.add(sys.stderr, format="{time:YYYY-MM-DD at HH:mm:ss} {level} {message}", filter="my_module", level="INFO")
logger.add("./log/gridIdToOrder.log", format="{time:YYYY-MM-DD at HH:mm:ss} | {level} | {message}", level="INFO")

# draw board
fig = plt.figure(1, (16, 9), dpi=120)
ax = plt.subplot(111)
plt.sca(ax)

start = time.time()

# 1.read order file
logger.info('读取原始订单文件')
order = pd.read_csv('E:/DataSet/zipcar_now/nextData/order.csv')
order['up_id'] = -1
order['off_id'] = -1
logger.info('原始订单文件形状:{}', order.shape)
print(order.head(1))

# read map
# map = geo.read_file('./map/NewYork.shp')
# map.plot(ax=ax, edgecolor=(0, 0, 0, 1), facecolor=(0, 0, 0, 0), linewidths=0.5)

# read grid geodataframe
grid = geo.read_file('E:/DataSet/zipcar_now/nextData/grid.shp')
logger.info('网格文件形状:{}', grid.shape)
print(grid.head(1))

order_o = geo.GeoDataFrame(order, geometry=geo.points_from_xy(order.up_lon, order.up_lat))
# print(order_o.head())

logger.info('为订单出发地划分网格')
for index, row in grid.iterrows():
    bord = row['geometry']
    # print(bord)
    order_o.loc[order_o.geometry.within(bord),'up_id'] = row['id']
    # order_o.loc[order_o[order_o.geometry.within(bord) & order_o.up_id != -1].index, 'up_id'] = row['id']
    # order_o.loc[order_o[order_o.up_id == -1 & order_o.geometry.within(bord)].index, 'up_id'] = row['id']
# print(order_o)

order_d = geo.GeoDataFrame(order_o, geometry=geo.points_from_xy(order_o.off_lon, order_o.off_lat))
# print(order_d.head())
logger.info('为订单到达地划分网格')
for index, row in grid.iterrows():
    bord = row['geometry']
    # print(bord)
    order_d.loc[order_d.geometry.within(bord),'off_id'] = row['id']
    # order_d.loc[order_d[order_d.geometry.within(bord) & order_d.off_id != -1].index, 'off_id'] = row['id']
    # order_d.loc[order_d[order_d.off_id == -1 & order_d.geometry.within(bord)].index, 'off_id'] = row['id']
# print(order_d)

order_d.drop(['geometry'], axis=1, inplace=True)
print(order_d.head(1))

# delete rows of up_id equeals off_id   删除出发和到达是同一个网格的订单
logger.info('删除od相同网格前订单数:{}', order_d.shape[0])
temp1 = order_d.loc[order_d.up_id == order_d.off_id, :]
order_d.drop(order_d[order_d.up_id == order_d.off_id].index, inplace=True)
temp12 = order_d.loc[order_d.up_id == order_d.off_id, :]
logger.info('删除od相同网格后订单数:{}', order_d.shape[0])
logger.info('出发和到达在同一个网格的订单数:{}', temp1.shape[0])

logger.info('删除后出发和到达在同一个网格的订单数:{}', temp12.shape[0])

# print(temp1.head())

temp2 = order_d.loc[order_d.up_id == -1, :]
logger.info('出发地不在网格内的订单:{}', temp2.shape[0])
# print(temp2.head())

temp3 = order_d.loc[order_d.off_id == -1, :]
logger.info('到达地不在网格内的订单:{}', temp3.shape[0])
# print(temp3.head())

order_d.to_csv('E:/DataSet/zipcar_now/nextData/gridIdOrder.csv', index=False)

# count program runtime
logger.info('run time:{}', time.time() - start, 's')

# show draw board
# plt.show()
